package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.AppUtil.CharUtil;
import com.example.demo.config.LocalDateTimeFormatConfig;
import com.example.demo.entity.AnToken;
import com.example.demo.mapper.AnTokenMapper;
import com.example.demo.service.IAnTokenService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户Token 服务实现类
 * </p>
 *
 * @author Mr.We
 * @since 2024-06-19
 */
@Service
public class AnTokenServiceImpl extends ServiceImpl<AnTokenMapper, AnToken> implements IAnTokenService {
    @Resource
    private AnTokenMapper anTokenMapper;
    @Resource
    private LocalDateTimeFormatConfig localDateTimeFormatConfig;
    /**
     * 30天过期
     */
    private final static Long EXPIRE = 3600 * 24 * 30L;

    @Override
    public AnToken queryByUserId(Long userId) {
        return anTokenMapper.queryByUserId(userId);
    }

    @Override
    public AnToken queryByToken(String token) {
        return anTokenMapper.queryByToken(token);
    }

    @Override
    public void update(AnToken token) {
        anTokenMapper.update(token);
    }

    @Override
    public Map<String, Object> createToken(long userId) {
        //生成一个token
        String token = CharUtil.getRandomString(32);
        //当前时间
        Date now = new Date();

        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //判断是否生成过token
        AnToken tokenEntity = queryByUserId(userId);
        if (tokenEntity == null) {
            tokenEntity = new AnToken();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(localDateTimeFormatConfig.convertDateToLocalDateTime(now));
            tokenEntity.setExpireTime(localDateTimeFormatConfig.convertDateToLocalDateTime(expireTime));

            //保存token
            save(tokenEntity);
        } else {
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(localDateTimeFormatConfig.convertDateToLocalDateTime(now));
            tokenEntity.setExpireTime(localDateTimeFormatConfig.convertDateToLocalDateTime(expireTime));

            //更新token
            update(tokenEntity);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", EXPIRE);

        return map;
    }

    @Override
    public boolean save(AnToken token) {
        if (token != null){
            anTokenMapper.insert(token);
            return true;
        }
        return false;
    }
}
